﻿using System;
using System.Configuration;
using System.Data.SqlClient;

namespace DateCenter.UpdateTool
{
    class Program
    {
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException +=
                new UnhandledExceptionEventHandler(UnhandledException);

            Logger.GetInstance().Info("开始更新数据中心");

            string connectionString0 = ConfigurationManager.ConnectionStrings["Connection0"].ConnectionString;
            string connectionString1 = ConfigurationManager.ConnectionStrings["Connection1"].ConnectionString;

            try
            {
                SqlTransaction trans = null;
                using (SqlConnection connection0 = new SqlConnection(connectionString0))
                {
                    connection0.Open();
                    using (SqlConnection connection1 = new SqlConnection(connectionString1))
                    {
                        connection1.Open();
                        trans = connection1.BeginTransaction();

                        using (SqlCommand command0 = connection0.CreateCommand())
                        {
                            using (SqlCommand command1 = connection1.CreateCommand())
                            {
                                command1.Transaction = trans;

                                UpdateBase update = new CenterUpdate();
                                UpdateDirector director = new UpdateDirector(command0, command1);
                                if (!director.Update(update))
                                {
                                    trans.Rollback();
                                    Logger.GetInstance().Info("数据中心更新失败");
                                }
                                else
                                {
                                    trans.Commit();
                                    Logger.GetInstance().Info("数据中心更新成功");
                                }                                
                            }
                        }
                    }
                }
                Console.Read();
            }
            catch (Exception ex)
            {
                Logger.GetInstance().Info("数据中心更新失败", ex);
            }
        }

        private static void UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = (Exception)e.ExceptionObject;
            Logger.GetInstance().Info(ex.Message);
            Logger.GetInstance().Info(ex.StackTrace);
            Console.Read();
        }
    }
}
